<template>
  <a-modal
    title="编辑分类"
    centered
    force-render
    ok-text="确认"
    cancel-text="取消"
    :mask-closable="false"
    :open="props.open"
    width="416"
    :confirm-loading="loading"
    @ok="onOk"
    @cancel="props.onCancel"
  >
    <div v-if="init" class="float-left text-center mt-30">
      <a-spin />
    </div>

    <div v-else class="float-left mt-24">
      <a-form
        ref="formRef"
        :model="formModel"
        name="resource-category-update"
        @finish="onFinish"
        @finishFailed="onFinishFailed"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
      >
        <a-form-item
          label="所属上级"
          name="parent_id"
          :rules="[{ required: true, message: '请选择所属上级!' }]"
        >
          <a-cascader
            v-model:value="formModel.parent_id"
            :options="categories"
            allow-clear
            placeholder="请选择所属上级"
            change-on-select
            expand-trigger="hover"
            :display-render="displayRender"
            @change="handleChange"
            style="width: 200px;"
          />
        </a-form-item>

        <a-form-item
          label="分类名称"
          name="name"
          :rules="[{ required: true, message: '请输入分类名称!' }]"
        >
          <a-input
            v-model:value="formModel.name"
            placeholder="请输入分类名称"
            allow-clear
            style="width: 200px;"
          />
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue';
import { message } from 'ant-design-vue';
import { resourceCategory } from '@/api/index';

interface Props {
  id: number;
  open: boolean;
  onCancel: () => void;
}

interface Option {
  value: string | number;
  label: string;
  children?: Option[];
}

const props = defineProps<Props>();

const formModel = reactive({
  name: '',
  parent_id: [] as (number | string)[],
});

const formRef = ref<any>(null);
const init = ref(true);
const loading = ref(false);
const categories = ref<Option[]>([]);
const sort = ref<number>(0);

watch(
  () => props.open,
  (val) => {
    if (val) {
      init.value = true;
      formModel.name = '';
      formModel.parent_id = [];
      loadCategories();
    }
  },
  { immediate: false }
);

const loadCategories = async () => {
  try {
    const res: any = await resourceCategory.createResourceCategory();
    const data = res.data.categories;
    let newArr: Option[] = [];
    if (JSON.stringify(data) !== '{}') {
      newArr = buildOptions(data, 0);
    }
    newArr.unshift({ label: '作为一级分类', value: 0 });
    categories.value = newArr;

    if (props.id && props.id !== 0) {
      await loadDetail(props.id);
    } else {
      init.value = false;
    }
  } catch (e) {
    console.error(e);
    init.value = false;
  }
};

const buildOptions = (categoriesData: any, id: number): Option[] => {
  const arr: Option[] = [];
  for (let i = 0; i < (categoriesData[id]?.length || 0); i++) {
    const item = categoriesData[id][i];
    if (!categoriesData[item.id]) {
      arr.push({ label: item.name, value: item.id });
    } else {
      arr.push({
        label: item.name,
        value: item.id,
        children: buildOptions(categoriesData, item.id),
      });
    }
  }
  return arr;
};

const loadDetail = async (id: number) => {
  try {
    const res: any = await resourceCategory.resourceCategory(id);
    const data = res.data;
    const arr = data.parent_chain
      ? data.parent_chain.split(',').filter(Boolean).map((n: string) => Number(n))
      : [];
    formModel.name = data.name || '';
    formModel.parent_id = arr;
    sort.value = data.sort || 0;
  } catch (e) {
    console.error(e);
  } finally {
    init.value = false;
  }
};

const onOk = () => {
  formRef.value
    ?.validate()
    .then(() => {
      onFinish(formModel);
    })
    .catch((err: any) => {
      console.log('表单校验失败', err);
    });
};

const onFinish = async (values: any) => {
  if (loading.value) return;
  loading.value = true;
  try {
    const parentId =
      values.parent_id && values.parent_id.length
        ? values.parent_id[values.parent_id.length - 1]
        : 0;

    await resourceCategory.updateResourceCategory(
      props.id,
      values.name,
      parentId,
      sort.value
    );

    message.success('保存成功！');
    props.onCancel();
  } catch (e) {
    console.error(e);
  } finally {
    loading.value = false;
  }
};

const onFinishFailed = (err: any) => {
  console.log('表单提交失败：', err);
};

const handleChange = (value: (string | number)[] | undefined) => {
  if (value && value.length > 0) {
    const last = value[value.length - 1];
    if (last === props.id) {
      message.error('不能选择自己作为父类');
      formModel.parent_id = [];
      return;
    }
    formModel.parent_id = value as (number | string)[];
  } else {
    formModel.parent_id = [];
  }
};

const displayRender = ({ labels }: { labels: string[] }) => {
  return labels.length ? labels[labels.length - 1] : '';
};

</script>

<style scoped>
.float-left {
  float: left;
}
.mt-24 {
  margin-top: 24px;
}
.mt-30 {
  margin-top: 30px;
}
.text-center {
  text-align: center;
}
</style>
